/****************************************************
          File Name:34-4.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 01 Sep 2014 11:01:53 AM CST
*****************************************************/

#define _GNU_SOURCE
#include<stdio.h>
#include<string.h>
#include<signal.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>

void dealing(int sig)
{
    printf("PID %ld: caught signal %2d (%s)\n",(long)getpid(),sig,strsignal(sig));
    // unsafe
}

int main(int argc,char *argv[])
{
    pid_t parent, child;
    int j;
    struct sigaction act;

    setbuf(stdout,NULL);

    parent=getpid();
    printf("PID of parent is: %ld\n",(long)parent);
    printf("FG process group ID is: %ld\n",(long)tcgetpgrp(STDIN_FILENO));

    for(j=1;j<argc;j++)
    {
        child=fork();
        if(child==-1)
        {
            perror("fork()");
            exit(1);
        }

        if(child==0)
        {
            if(argv[j][0]=='d')
                if(setpgid(0,0)==-1)
                {
                    perror("setpgid");
                    exit(1);
                }
            sigemptyset(&act.sa_mask);
            act.sa_flags=0;
            act.sa_handler=dealing;
            if(sigaction(SIGHUP,&act,NULL)==-1)
            {
                perror("sigaction");
                exit(1);
            }
            break;
        }
    }

    alarm(60);

    /*
     * 此处忽略SIGHUP，内核不会向前台进程组发送SIGHUP
     */
    signal(SIGHUP,SIG_IGN); 
    printf("PID=%ld PGID=%ld\n",(long)getpid(),(long)getpgrp());

    for(;;)
        pause();
}
